package example.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import example.exception.TokenAuthExpiredException;
import example.pojo.User;
import example.service.UserService;
import example.util.TokenUtil;


import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    TokenUtil tokenUtil;
    @Autowired
    private UserService userService;
    @Value("${token.privateKey}")
    private String privateKey;
    @Value("${token.yangToken}")
    private Long yangToken;
    @Value("${token.oldToken}")
    private Long oldToken;
    /**
     * 权限认证的拦截操作.
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {

        //解决办法就是加上这一行代码，跨域访问允许访问的响应头的内容
        httpServletResponse.setHeader("Access-Control-Expose-Headers","token");

        log.info("=======进入拦截器========");
        // 如果不是映射到方法直接通过,可以访问资源.
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        //为空就返回错误
        String token = httpServletRequest.getHeader("token");
        if (null == token || "".equals(token.trim())) {
            // 执行认证
            throw new RuntimeException("无token，请重新登录");
//            return false;
        }
        log.info("==============token:" + token);

        // 获取 token

       Map<String, String> map = tokenUtil.parseToken(token);
//        String userId = map.get("userId");
//        String userRole = map.get("userRole");
        String name = map.get("name");
        long timeOfUse = System.currentTimeMillis() - Long.parseLong(map.get("timeStamp"));

        //1.判断 token 是否过期
        //年轻 token
        if (timeOfUse < yangToken) {
            log.info("年轻 token");
            httpServletResponse.setHeader("token",token);
        }
        //老年 token 就刷新 token
        else if (timeOfUse >= yangToken && timeOfUse < oldToken) {
//            httpServletResponse.setHeader("token",tokenUtil.getToken(userId,userRole));
            httpServletResponse.setHeader("token",tokenUtil.getToken(name));
        }
        //过期 token 就返回 token 无效.
        else {
            throw new TokenAuthExpiredException();

        }
// 2,用户存在判断
        User user= new User();
        user.setName(name);
        List<User> list=null;
        if (user != null && user.getName() != null && user.getName() != "") {
            list = userService.getUserlistByName(user);
        }
        if (list == null) {
            throw new RuntimeException("用户不存在，请重新登录");
        }
//        //3.角色匹配.
//        if ("user".equals(userRole)) {
//            log.info("========user账户============");
//            return true;
//        }
//        if ("admin".equals(userRole)) {
//            log.info("========admin账户============");
//            return true;
//        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

}